package pers.li.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BeanCopy {
    public static final String GET = "get";
    public static final String SET = "set";

    public static void copy(Object srcObj, Object tagObj) {
        Class<?> srcObjClass = srcObj.getClass();
        Class<?> tagObjClass = tagObj.getClass();
        Field[] tagFields = tagObjClass.getDeclaredFields();

        for (Field tagField : tagFields) {
            String tfn = tagField.getName();
            try {
                srcObjClass.getDeclaredField(tfn);
                Class<?> tagFieldType = tagField.getType();
                String setMethodName = getMethodName(SET,tfn);
                String getMethodName = getMethodName(GET,tfn);
                try {
                    Method getMethod = srcObjClass.getMethod(getMethodName);
                    Method setMethod = tagObjClass.getMethod(setMethodName,tagFieldType);
                    try {
                        setMethod.invoke(tagObj,getMethod.invoke(srcObj));
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            } catch (NoSuchFieldException ignored) {
            }
        }
    }

    public static String getMethodName(String command, String srcName) {
        return command + srcName.substring(0, 1).toUpperCase() + srcName.substring(1);
    }
}
